
load('js/luaclient.js')
var billDate = "";// 账单日
var sdfBill = new SimpleDateFormat("YYYY-MM");

var v4_beijing_credit_java_funcs = {
    openHomePage : function(){
        //访问首页
        var indexHtml = get("https://card.bankofbeijing.com.cn/bobbank/");
        storeDataToFile(context, indexHtml, "index.html");
        //页面不为空
        context.put("indexHtml", indexHtml)
    },
    checkProxyAvailable: function () {

        var indexHtml = context.get("indexHtml")
        if(StringUtils.isBlank(indexHtml)) {
            return false
        }
        var doc = Jsoup.parse(indexHtml)
        logger.info("任务【 {} 】标题='{}'", context.get(LUA_TASK_KEY), doc.select("title").text())
        logger.info("任务【 {} 】id='username'的元素个数{}", context.get(LUA_TASK_KEY), doc.select("#username").size())

        return equals(doc.select("title").text(), "北京银行在线账户系统 北京银行在线账户系统") && doc.select("#username").size() > 0
    },
    checkTargetWebsiteAvailable: function(){ return true },
    checkControlAvailable:function (){ return true},
    //只有在图片验证码错误或短信验证码错误　　重置环境
    needResetEnvironment :function () {
      return  equals(context.get("currentErrorCode"),BALO_99602_50) || equals(context.get("currentErrorCode"),BALO_99602_40);
    },
    login: function() {

        // show()
        // 输入用户名密码
        luaFuncs.input_account(getLoginParams(context)[0], context.get(LUA_TASK_TOKEN))

        //发送短信
        var alertMsg = luaFuncs.clickSms(); // 获取alert中的内容
        logger.info("点击短信时出现的:{}", alertMsg);

        var isSmsSendCorrectFuncs = function(alertMsg) {
            return alertMsg.contains("短信成功发送")
        }

        var getSmsSendErrMsgFuncs = function(alertMsg) {
            return alertMsg
        }

        assertTrueOrThrowException(alertMsg, isSmsSendCorrectFuncs, getSmsSendErrMsgFuncs)
        logger.info("任务【 {} 】短信发送成功", context.get(LUA_TASK_KEY))


        //接收短信
        var smsCode = waitSmsCodeBySeconds(context,120);
        // 给短信框输入内容
        set_input_text_by_id("smscode", smsCode);

        var smsCodeInputResult = luaFuncs.checkIfInput("smscode",smsCode);

        var isSmsCodeInputCorrectFunc = function(smsCodeInputResult) {
            return smsCodeInputResult
        }

        var getSmsCodeInputErrorMsgFunc = function(smsCodeInputResult) {
            return "短信验证码错误"
        }
        assertTrueOrThrowException(smsCodeInputResult, isSmsCodeInputCorrectFunc, getSmsCodeInputErrorMsgFunc)
        logger.info("任务【 {} 】短信验证码输入成功", context.get(LUA_TASK_KEY))


        //获取图片验证码
        var captchaPath = get_image_by_id("pwPic");

        logger.info("任务【 {} 】图片验证码路径【 {} 】", context.get(LUA_TASK_KEY), captchaPath)
        var isCaptchaPathCorrectFunc = function(captchaPath) {
            return captchaPath !== null && captchaPath !== undefined && captchaPath !== 'path fail'
        }

        var getCaptchaPathErrorMsgFunc = function(captchaPath) {
            return "图片验证码获取失败"
        }
        assertTrueOrThrowException(captchaPath, isCaptchaPathCorrectFunc, getCaptchaPathErrorMsgFunc)
        logger.info("任务【 {} 】图片验证码获取成功", context.get(LUA_TASK_KEY))

        //识别及判定
        context.put(TASK_IMG_PATH, captchaPath);
        context.put(TASK_IMG_REGEX,"[0-9]{6}");
        var imgCode = waitImgCodeBySecondsByJs(context,60,true,3);

        var isImgCodeCorrectFunc = function(imgCode) {
            return StringUtils.isNotBlank(imgCode) && imgCode.length === 6
        }

        var getImgCodeErrorMsgFunc = function(imgCode) {
            return "图片验证码错误"
        }
        assertTrueOrThrowException(imgCode, isImgCodeCorrectFunc, getImgCodeErrorMsgFunc)
        logger.info("任务【 {} 】图片验证码格式正确", context.get(LUA_TASK_KEY))

        show();
        //输入验证码
        set_input_text_by_id_event("code", imgCode);

        hide();

        var imgCodeInputResult = luaFuncs.checkIfInput("code",imgCode);

        var isImgCodeInputCorrectFunc = function(imgCodeInputResult) {
            return imgCodeInputResult
        }

        var getImgCodeInputErrorMsgFunc = function(imgCodeInputResult) {
            return "图片验证码未输入"
        }
        assertTrueOrThrowException(imgCodeInputResult, isImgCodeInputCorrectFunc, getImgCodeInputErrorMsgFunc)
        logger.info("任务【 {} 】图片验证码输入成功", context.get(LUA_TASK_KEY))


        //登录并判断是否成功
        var jsonObject = JSON.parseObject(luaFuncs.clickLoginBtn());

        var isLoginCorrectFuncs = function(jsonObject) {
            return Boolean.valueOf(jsonObject.get("login_result"))
        }

        var getLoginErrMsgFuncs = function(jsonObject) {
            return jsonObject.get("error_msg")
        }
        assertTrueOrThrowException(jsonObject, isLoginCorrectFuncs, getLoginErrMsgFuncs)
        logger.info("任务【 {} 】登录成功", context.get(LUA_TASK_KEY))

    },
    crawl:function () {
        logger.info("{},北京信用卡抓取程序开始", context.get(LUA_TASK_KEY));
        Thread.sleep(3000);
        var creditCardAllDataList = new ArrayList();
        var creditCardAllData = new CreditCardAllData();
        var  billAllDatas = new ArrayList();
        creditCardAllData.setBills(billAllDatas);

        basicInfo(creditCardAllData);
        billInfoCrawl(creditCardAllData);
        billOutInfoCrawl(creditCardAllData);

        creditCardAllDataList.add(creditCardAllData);
        context.put(CREDIT_DATA, creditCardAllDataList);
    },
    exitLogin: function () {}
}


/***
 * 未出账单
 */
function billOutInfoCrawl(creditCardAllData) {
    logger.info("{},北京银行信用卡未出账单抓取", context.get(LUA_TASK_KEY));
    try {
        var billAllData = new BillAllData();
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBillType("UNDONE");
        billAllData.setBankName("北京银行");
        var expenses = new ArrayList();
        billAllData.setShoppingSheets(expenses);
        var installments =  new ArrayList();
        billAllData.setInstallments(installments);

        var calendar = Calendar.getInstance();
        var day = calendar.get(Calendar.DAY_OF_MONTH);
        day = Integer.parseInt(day);
        var billOutDate = "";
        if (billDate !== ""&& null !== billDate) {
            if (day > Integer.parseInt(billDate)) {
                calendar.add(Calendar.MONTH, 1);
            }
            billOutDate = sdfBill.format(calendar.getTime());
        }
        billAllData.setBillMonth(billOutDate);
        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billOutDate + "-" + billDate));

        var undoneURL = "https://card.bankofbeijing.com.cn/bobbank//billmng/unbill/index";
        var unDoneData = new HashMap();
        unDoneData.put("cardSeq", "1");
        unDoneData.put("currency", "L");
        // 未出账单
        var unDoneHtml = ajax_post(undoneURL, unDoneData);
        storeDataToFile(context,unDoneHtml, "unDoneHtml.html");

        var unDoneDoc = Jsoup.parse(unDoneHtml);
        // 本期帐单金额
        var newCharges = unDoneDoc.select("td.value:nth-child(2)").text().trim().replaceAll(",", "");
        billAllData.setNewCharges(new BigDecimal(newCharges));// 本期账单金额
        billAllData.setCashLimit(creditCardAllData.getCashLimit());// 预借现金额度
        billAllData.setCreditLimit(creditCardAllData.getCreditLimit());// 信用卡额度
        billAllData.setUsdNewBalance(null);
        billAllData.setUsdLastBalance(null);
        billAllData.setUsdLastPayment(null);
        billAllData.setUsdNewCharges(null);
        billAllData.setUsdInterest(null);
        billAllData.setUsdCreditLimit(null);
        billAllData.setUsdCashLimit(null);
        billAllData.setUsdMinPayment(null);
        billAllData.setMinPayment(null);

        billAllData.setInterest(null);
        // 没有last_payment(上期还款金额)(这个应该在未出账单中取)  没有就取null
        billAllData.setLastPayment(null);
        // 上期还款金额
        var lastBalance = context.get("newBalance");
        billAllData.setLastBalance(( null !== lastBalance) ? new BigDecimal(lastBalance)
            : new BigDecimal(0.0));
        // 未出账单明细
        var unDoneShoppingJson = ajax_post(
            "https://card.bankofbeijing.com.cn/bobbank/billmng/unbill/pages", new HashMap());
        storeDataToFile(context,unDoneShoppingJson, "unDoneShopping.json");

        var sumAmountMoney = 0.0;
        if (!equals("[]",unDoneShoppingJson) || null !== unDoneShoppingJson) {

            var unDoneShoppingJsonArray = JSON.parseArray(unDoneShoppingJson);
            var mapUnDoneListJson =  unDoneShoppingJsonArray;
            // json字符串的长度 相当于有多少条消费记录
            var index = 0;
            for (var i = 0; i < mapUnDoneListJson.size(); i++) {
                var expense = new Expense();
                // 获取每条的消费记录
                var unDoneItemEvery = mapUnDoneListJson.get(i);
                //交易时间
                var transDate = unDoneItemEvery.get("val_Date").trim();
                //卡号后四位
                var cardNum = unDoneItemEvery.get("cardEnd").trim();
                //消费
                var amountMoney = unDoneItemEvery.get("amount").trim().replaceAll(",", "");
                //描述
                var description = unDoneItemEvery.get("descline1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");

                expense.setId(UUID.randomUUID().toString());
                expense.setCardNum(cardNum);
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(transDate));
                expense.setCategory(CategoryUtil.getCreditCategory("BEIJING", description, amountMoney));
                expense.setOrderIndex(++index);
                expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate + " 00:00:00"));
                expense.setCurrencyType("CNY");
                expense.setAmountMoney(new BigDecimal(amountMoney));
                //对方持卡人
                expense.setNameOnOppositeCard("");
                //对方银行卡
                expense.setOppositeBank("");
                //对方卡号
                expense.setOppositeCardNo("");
                //备注
                expense.setRemark("");
                //交易通道
                expense.setTransChannel("");
                //交易方式
                expense.setTransMethod("");
                //交易地点
                expense.setTransAddr("");
                //未出帐单所有的金额
                sumAmountMoney = sumAmountMoney + Double.parseDouble(amountMoney);
                expense.setBalance(null);
                expense.setDescription(description);
                // 把每条消费记录添加到集合中
                billAllData.getShoppingSheets().add(expense);
            }
        }

        var newBalance = sumAmountMoney + Double.parseDouble(lastBalance);
        //未出帐单中的new_balance
        billAllData.setNewBalance(new BigDecimal(String.format("%.2f", newBalance)));
        creditCardAllData.getBills().add(billAllData);
    } catch (e) {
        logger.error("{}，北京银行信用卡未出账单抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 已出账单
 */
function billInfoCrawl(creditCardAllData) {
    logger.info("{},北京银行信用卡已出账单抓取", context.get(LUA_TASK_KEY));

    var dateEveryList = getRecentMonth();
    Collections.reverse(dateEveryList);// 将集合的顺序颠倒,为了得到最后集合中最大的月份中的本期账单金额
    for (var i = 0; i < dateEveryList.size(); i++) {
        var dateEvery = dateEveryList.get(i);// 获取每个月
        var billAllData = new BillAllData();
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBillType("DONE");
        billAllData.setBankName("北京银行");
        billAllData.setBillMonth(dateEvery);// yyyy-MM
        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(dateEvery + "-" + billDate));
        var expenses = new  ArrayList();
        billAllData.setShoppingSheets(expenses);// 消费
        var installments = new ArrayList();
        billAllData.setInstallments(installments);// 分期
        // 信用额度相关
        billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
        billAllData.setCashLimit(creditCardAllData.getCashLimit());

        saveBillDetail(creditCardAllData, billAllData, dateEvery, dateEveryList);

        creditCardAllData.getBills().add(billAllData);// 把billAllData添加到集合中
    }

}

/**
 * 已出账单详细记录
 */
function  saveBillDetail( creditCardAllData,  billAllData,  dateEvery, dateEveryList) {
    logger.info("{},抓取{}账单", context.get(LUA_TASK_KEY), dateEvery);
    try {
        dateEvery = dateEvery.replaceAll("-", "");

        var billURL = "https://card.bankofbeijing.com.cn/bobbank/billmng/bill/index";
        var postData = new HashMap();
        postData.put("cardSeq", "1");
        postData.put("currency", "L");
        postData.put("year", dateEvery);
        postData.put("date", dateEvery);
        postData.put("stmtdate", dateEveryList.get(0).replaceAll("-", ""));
        // 每月账单
        var billDateEveryHtml = ajax_post(billURL, postData);
        storeDataToFile(context,billDateEveryHtml, "bill" + dateEvery + ".html");
        // 每月账单明细
        var billDateShoppingJson = ajax_post(
            "https://card.bankofbeijing.com.cn/bobbank/billmng/bill/pages", new HashMap());
        storeDataToFile(context,billDateShoppingJson, "bill" + dateEvery + "Shopping.json");

        var billDateEveryDoc = Jsoup.parse(billDateEveryHtml);
        // 最低还款金额
        var minPayment = billDateEveryDoc
            .select(".tabA > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(4)").text().trim()
            .replaceAll(",", "");
        // 上期还款金额""
        var lastPayment = billDateEveryDoc.select(".w172").text().trim().replaceAll(",", "");
        // 还款日""
        var paymentDate = billDateEveryDoc.select("td.c-red:nth-child(4)").text().trim();
        // 本期应还金额
        var newBalance = billDateEveryDoc
            .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1)")
            .text().trim().replaceAll(",", "");
        context.put("newBalance", newBalance);
        // 上期账单金额
        var lastBalance = billDateEveryDoc
            .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(3)")
            .text().trim().replaceAll(",", "");
        // 本期帐单金额
        var newCharges = billDateEveryDoc
            .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(7)")
            .text().trim().replaceAll(",", "");
        // 循环利息
        var interest = billDateEveryDoc
            .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(11)")
            .text().trim();

        billAllData.setMinPayment(new BigDecimal(minPayment));
        billAllData.setLastPayment(!equals(lastPayment,"") ? new BigDecimal("-" + lastPayment) : null);
        if(!equals(paymentDate,"")){
            billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(paymentDate));
        }
        billAllData.setNewBalance(new BigDecimal(newBalance));
        billAllData.setLastBalance(new BigDecimal(lastBalance));
        billAllData.setNewCharges(new BigDecimal(newCharges));
        billAllData.setInterest(new BigDecimal(interest));
        // billAllData.setInterest(null);
        billAllData.setUsdNewBalance(null);
        billAllData.setUsdLastBalance(null);
        billAllData.setUsdLastPayment(null);
        billAllData.setUsdNewCharges(null);
        billAllData.setUsdInterest(null);
        billAllData.setUsdCreditLimit(null);
        billAllData.setUsdCashLimit(null);
        billAllData.setUsdMinPayment(null);

        if (equals("[]",billDateShoppingJson) || null == billDateShoppingJson) {
            return;
        }

        var billDateShoppingJsonArray = JSON.parseArray(billDateShoppingJson);
        var mapListJson =  billDateShoppingJsonArray;


        //分期第一次出现的位置  如果小于 手续费第一次出现的位置   证明  分期在手续费前面
        //分期第一次出现的位置  如果大于 手续费第一次出现的位置    证明  分期在手续费后面 需要反转
        var fenqiIndex= mapListJson.toString().indexOf("分期") ;
        var shouxufeiIndex =  mapListJson.toString().indexOf("手续费");
        if(fenqiIndex > shouxufeiIndex){
            Collections.reverse(mapListJson);
        }


        var index = 0;
        // json字符串的长度 相当于有多少条消费记录
        var originalNewCharges = 0.0;
        for (var i = 0; i < mapListJson.size(); i++) {
            var expense = new Expense();
            var jsonItemEveryDate = mapListJson.get(i);
            // 卡号后四位
            var cardNum = jsonItemEveryDate.get("cardEND").trim();
//				logger.info("卡号后四位:{}", cardNum);
            // 金额
            var amountMoney = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
//				logger.info("金额:{}", amountMoney);
            /*
             * new_charges 页面上有  但不直接取值  因为页面上的值不准确 所以要计算
             */
            if(!amountMoney.contains("-")){
                originalNewCharges = originalNewCharges +  Double.parseDouble(amountMoney);
            }

            // 描述
            var tranDESLINE1 = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
            var tranDESLINE2 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
            var description = tranDESLINE1 + tranDESLINE2;
            logger.info("{},描述:{}", context.get(LUA_TASK_KEY), description);
            // 交易日
            var transDate = jsonItemEveryDate.get("val_DATE").trim();
//				logger.info("交易日:{}", transDate);
            //如果描述中出现账单分期手续费,就将分期手续费和描述用map集合装起来  待等到当前分期为1的时候再放进去
            //因为这个分期手续费是总共的
            if (description.contains("分期手续费")) {
                logger.info("-----分期手续费:{}", description);
                context.put("amountMoney", amountMoney);
                context.put("description", description);
            }
            expense.setId(UUID.randomUUID().toString());
            expense.setCardNum(cardNum);
            expense.setBalance(null);
            // 记帐日
            expense.setPostDate(yyyy_MM_dd_PARSER.parse(transDate));
            // 消费类型
            expense.setCategory(CategoryUtil.getCreditCategory("BEIJING", description, amountMoney));
            // 排序
            expense.setOrderIndex(++index);
            // 交易时间
            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate + " 00:00:00"));
            // 币种
            expense.setCurrencyType("CNY");
            // 消费金额
            expense.setAmountMoney(new BigDecimal(amountMoney));
            // 描述
            expense.setDescription(description);
            //对方持卡人
            expense.setNameOnOppositeCard("");
            //对方银行卡
            expense.setOppositeBank("");
            //对方卡号
            expense.setOppositeCardNo("");
            //备注
            expense.setRemark("");
            //交易通道
            expense.setTransChannel("");
            //交易方式
            expense.setTransMethod("");
            //交易地点
            expense.setTransAddr("");
            if (isNumExists(description) && (description.contains("账单分期") || description.contains("灵活分期") || (description.contains("灵动金") && !description.contains("手续费")))) {

                if (getFen(description).size() > 1) {
                    var installment = new Installment();
                    billAllData.getInstallments().add(installment);
                    installment.setShoppingsheetId(UUID.randomUUID().toString());
                    //金额
                    installment.setAmountMoney(new BigDecimal(amountMoney));
                    //记帐日
                    installment.setPostDate(yyyy_MM_dd_PARSER.parse(transDate));
                    //交易日
                    installment.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate + " 00:00:00"));
                    //分期描述
                    installment.setInstallmentDesc(description);
                    //分期转帐手续费描述
                    installment.setTransferfeeDesc("");
                    //分期类型
                    installment.setInstallmentType(installmentTypeChange(description));
                    //币种
                    installment.setCurrencyType(expense.getCurrencyType());
                    // 转账手续费
                    installment.setTransferFee(null);
                    if (getFen(description).size() == 2) {
                        //当前分期数
                        installment.setCurrentMonth(getFen(description).get(0));
                        // 总分期数
                        installment.setTotalMonth(getFen(description).get(1));
                    } else if (getFen(description).size() == 3) {//灵动金
                        //当前分期数
                        installment.setCurrentMonth(getFen(description).get(1));
                        // 总分期数
                        installment.setTotalMonth(getFen(description).get(2));
                    }
                    if (description.contains("账单分期") || description.contains("灵活分期")) {
                        //如果当前分期为1的时候 就把集合里的取出来    其他的是null
                        if (getFen(description).get(0) == 1) {
                            if((i + 1) < mapListJson.size() ) {
                                var jsonItemEveryDate = mapListJson.get(i + 1);
                                var amountMoney1 = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
                                var tranDESLINE = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                var tranDESLINE3 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                var insDes = tranDESLINE + tranDESLINE3;
                                logger.info("{},下一条描述:{}",context.get(LUA_TASK_KEY),insDes);
                                if (insDes.contains("手续费")) {
                                    //分期金额
                                    installment.setHandingFee(new BigDecimal(amountMoney1));
                                    //分期手续费描述
                                    installment.setHandingfeeDesc(insDes);
                                }else {
                                    //分期金额
                                    installment.setHandingFee(null);
                                    //分期手续费描述
                                    installment.setHandingfeeDesc("");
                                }
                            }else if((i + 1) == mapListJson.size()){
                                var jsonItemEveryDate = mapListJson.get(i);
                                var amountMoney1 = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
                                var tranDESLINE = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                var tranDESLINE3 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                var insDes = tranDESLINE + tranDESLINE3;
                                logger.info("{},上一条描述:{}",context.get(LUA_TASK_KEY),insDes);
                                if (insDes.contains("手续费")) {
                                    //分期金额
                                    installment.setHandingFee(new BigDecimal(amountMoney1));
                                    //分期手续费描述
                                    installment.setHandingfeeDesc(insDes);
                                }else {
                                    //分期金额
                                    installment.setHandingFee(null);
                                    //分期手续费描述
                                    installment.setHandingfeeDesc("");
                                }

                            }
                        }else {
                            //分期金额
                            installment.setHandingFee(null);
                            //分期手续费描述
                            installment.setHandingfeeDesc("");
                        }
                    }


                    /*//分期手续费和分期手续费描述
                     if((i + 1) <= mapListJson.size()){
                     if((i + 1) == mapListJson.size()){
                     Map<String, String> installmentMapJson = mapListJson.get(i);
                     //分期手续费
                     String installmentAmountMoney = installmentMapJson.get("tranAMOUNT").replace(",", "").trim();// -365.9
                     //分期手续费描述
                     String installmentTranDESLINE1 = installmentMapJson.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                     String installmentTranDESLINE2 = installmentMapJson.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                     String handingfeeDesc = installmentTranDESLINE1 + installmentTranDESLINE2 ;
                     logger.info("{},分期手续费描述:{}",this.parameter.(String) this.getBizParameter().get(Constants.LUA_TASK_KEY)(),handingfeeDesc);
                     if(handingfeeDesc.contains("分期手续费")){
                     //分期手续费
                     installment.setHandingFee(!"".equals(installmentAmountMoney) ? new BigDecimal(installmentAmountMoney): null);
                     //分期手续费描述
                     installment.setHandingfeeDesc(handingfeeDesc);
                     }
                     }else {
                     Map<String, String> installmentMapJson = mapListJson.get(i + 1);
                     //分期手续费
                     String installmentAmountMoney = installmentMapJson.get("tranAMOUNT").replace(",", "").trim();// -365.9
                     //分期手续费描述
                     String installmentTranDESLINE1 = installmentMapJson.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                     String installmentTranDESLINE2 = installmentMapJson.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                     String handingfeeDesc = installmentTranDESLINE1 + installmentTranDESLINE2 ;
                     logger.info("{},分期手续费描述:{}",this.parameter.(String) this.getBizParameter().get(Constants.LUA_TASK_KEY)(),handingfeeDesc);
                     if(handingfeeDesc.contains("分期手续费")){
                     //分期手续费
                     installment.setHandingFee(!"".equals(installmentAmountMoney) ? new BigDecimal(installmentAmountMoney): null);
                     //分期手续费描述
                     installment.setHandingfeeDesc(handingfeeDesc);
                     }
                     //TODO:要做上条是不是分期手续费
                     }
                     if(getFen(description).get(0) == 1){
                     //分期手续费
                     installment.setHandingFee(null);
                     //分期手续费描述
                     installment.setHandingfeeDesc("");
                     }
                     }*/
                }
            } else if (description.contains("灵动金") && description.contains("手续费")) {
                //判断分期费和分期手续费是不是同一个对象
                var ins = findExistInstallment(billAllData.getInstallments(), description);
                logger.info("灵动金的分期手续费描述:{},分期对象:{}", description, ins);
                //是将分期的集合遍历一下 找到灵动金的分期   如果找到灵动金的分期描述   将判断分期描述的当期分期和灵动金的分期手续费描述当期不分期是不是同一个分期
                //如果是同一个分期  就添加到
                var list = billAllData.getInstallments();
                for each(var in_fee in list) {
                    if (in_fee.getInstallmentDesc().contains("灵动金")) {

                        if (getFen(in_fee.getInstallmentDesc()).get(1) == getFen(description).get(1) && ins !== null) {
                            ins.setHandingFee(expense.getAmountMoney());
                            ins.setHandingfeeDesc(description);
                        }
                    }else{
                        ins.setHandingFee(!equals("",context.get("amountMoney")) && null !== context.get("amountMoney") ? new BigDecimal(context.get("amountMoney")) : null);
                        ins.setHandingfeeDesc(context.get("description"));
                    }
                }
            }

            billAllData.getShoppingSheets().add(expense);
        }
        logger.info("{},setNewCharges={}",context.get(LUA_TASK_KEY),originalNewCharges);
        // billAllData.setNewCharges(new BigDecimal(String.format("%.2f",originalNewCharges)));
    } catch (e) {
        logger.error("{}，北京银行信用卡{}账单抓取异常：{}", context.get(LUA_TASK_KEY), dateEvery, e);
        statCaughtException(context, e);
    }

}

/**
 * 给已出账单中的分期找对应关系
 *
 * @param installments 是不包含手续费
 * @param description  包含手续费
 * @return
 */
function  findExistInstallment(installments,  description) {
    // TODO Auto-generated method stub
    for each(var installment in installments) {
        if (installment.getInstallmentDesc().contains("灵动金") && description.contains("灵动金")) {
            return installment;
        }
    }
    return null;
}

/**
 * 基本信息
 */
function basicInfo(creditCardAllData) {
    try {
        logger.info("{},北京银行信用卡基本信息开始抓取", context.get(LUA_TASK_KEY));
        creditCardAllData.setCardId(UUID.randomUUID().toString());
        creditCardAllData.setCardType("信用卡");
        creditCardAllData.setBankName("北京银行");
        creditCardAllData.setDeposits(new ArrayList());// 这个是借记卡才有的
//			String accountInfoHtml = client.accountInfo();
        var accountURL = "https://card.bankofbeijing.com.cn/bobbank/acctmng/acctqry";
        var accountData = new HashMap();
        accountData.put("menuId", "2000");
        accountData.put("pmenuId", "m2");
        var accountInfoHtml = ajax_post(accountURL, accountData);
        // logger.info("帐户页面:{}",accountInfo);
        storeDataToFile(context, accountInfoHtml, "accountInfo.html");
        var accountDoc = Jsoup.parse(accountInfoHtml);
        // 持卡人
        var name = accountDoc
            .select("#main > div.pt10 > div.f14 > table > tbody > tr:nth-child(1) > td:nth-child(2)").text()
            .trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");


        // 信用卡额度
        var creditLimit = accountDoc.select("#ax_creditLimit").text().trim().replaceAll(",", "");// 信用卡额度
        // 信用卡可用额度
        var balance = accountDoc.select("#ax_avLimit").text().trim().replaceAll(",", "");
        // 信用卡现金总额度
        var cashLimit = accountDoc.select("#ax_caLimit").text().trim().replaceAll(",", "");
        // 信用卡现金可用额度
        // String cashBalance = zhuanghuDoc.select("").text().trim();
        // 账单日
        billDate = accountDoc.select("#ax_cyclNbr").text().trim();
        logger.info("持卡人:{}", name);

        creditCardAllData.setNameOnCard(name);// 持卡人
        creditCardAllData.setFullCardNum(cardListFunc(accountDoc));// 完整卡号
        creditCardAllData.setCardNum(cardNum(accountDoc));// 卡号后四位
        creditCardAllData.setCreditLimit(new BigDecimal(creditLimit));// 信用卡额度
        creditCardAllData.setBalance(new BigDecimal(balance));// 信用卡可用额度
        creditCardAllData.setCashLimit(new BigDecimal(cashLimit));// 信用卡现金总额度
        creditCardAllData.setCashBalance(null);
        creditCardAllData.setOpenBank("");



    } catch (e) {
        logger.error("{}，北京银行信用卡基本信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 卡号集合
 */
function cardListFunc(accountDoc) {
    var sb = new StringBuffer();
    //全部为数字的正则表达式
    var numStr = "^[0-9]*$";
    //判断有几个卡号
    var  cardSize = accountDoc.select(".sel > option").size();
    logger.info("{},==有{}个卡号", context.get(LUA_TASK_KEY),cardSize);
    for(var i = 1; i <= cardSize; i ++){
         var fullCardNum = accountDoc.select(".sel > option:nth-child("+i+")").text();
         //此处判断卡号是否包含*号,
         if(fullCardNum.contains("*") ){
            sb.append(fullCardNum).append(",");
        }
         //全部是数字
        if (fullCardNum.matches(numStr)){
            sb.append(fullCardNum).append(",");
        }
     }
    return sb.toString().substring(0,sb.toString().lastIndexOf(","));
}
/**
 * 卡后四位
 */
function cardNum(accountDoc) {
    var sb = new StringBuffer();
    //判断有几个卡号
    var  cardSize = accountDoc.select(".sel > option").size();
    logger.info("{},>>>>有{}个卡号", context.get(LUA_TASK_KEY),cardSize);
    for(var i = 1; i <= cardSize; i ++){
        var fullCardNum = accountDoc.select(".sel > option:nth-child("+i+")").text();
        logger.info("{},第{}个卡号:{}",context.get(LUA_TASK_KEY),i,fullCardNum)
        if(fullCardNum.contains("*")){
            sb.append(fullCardNum.substring((fullCardNum.length() - 4), (fullCardNum.length()))).append(",");
        }

    }
    return sb.toString().substring(0,sb.toString().lastIndexOf(","));
}


/**
 * 银行只能查7个月
 *
 * @return
 */
function  getRecentMonth() {
    var dateList = new ArrayList();
    var calendar = Calendar.getInstance();
    for (var i = 0; i < 7; i++) {
        var day = calendar.get(Calendar.DAY_OF_MONTH);
        day = Integer.parseInt(day);
        if (!equals("",billDate) && null !== billDate) {
            if (day <= Integer.parseInt(billDate)) {
                calendar.add(Calendar.MONTH, -1);
                dateList.add(sdfBill.format(calendar.getTime()));
            } else {
                dateList.add(sdfBill.format(calendar.getTime()));
                calendar.add(Calendar.MONTH, -1);
            }
        }
    }
    return dateList;
}

/**
 * 把分期描述里的数字提取出来或提取未出账单中的总页和当前页
 *
 * @param des
 * @return
 */
function   getFen(des) {
    var list = new ArrayList();
    var r = Pattern.compile("\\d+");
    var m = r.matcher(des);
    while (m.find()) {
        list.add(Integer.parseInt(m.group()));
    }
    return list;
}

/**
 * 判断字符串里面是否包含数字
 *
 * @param description
 * @return
 */
function isNumExists(description) {

    return description.matches(".*\\d+.*");
}

/**
 * 根据登录方式返回登录信息
 */
function getLoginText()  {
    var card = getLoginParams(context)[0];//卡号
    var idCard = getLoginParams(context)[1];//身份证
    // 卡号
    if (equals(CARDNOANDIDCARD,LoginType.stringToLoginType(context.get(LUA_TASK_LOGIN_TYPE)))) {
        logger.info("北京银行登录方式，taskKey:{}, loginType:{}", context.get(LUA_TASK_KEY),
            context.get(LUA_TASK_LOGIN_TYPE));
        if (IDCardReg.IDCardValidate(card)) {
            return idCard;
        } else {
            //
            return card;
        }

    } else if (equals(LoginType.IDCARD,LoginType.stringToLoginType(context.get(LUA_TASK_LOGIN_TYPE)))) {
        logger.info("北京银行该登录方式，taskKey:{}, loginType:{}", context.get(LUA_TASK_KEY),
            context.get(LUA_TASK_LOGIN_TYPE));
        if (IDCardReg.IDCardValidate(card)) {
            return card;
        } else {
            //
            return idCard;
        }
    } else if (equals(LoginType.USERNAME,LoginType.stringToLoginType(context.get(LUA_TASK_LOGIN_TYPE)))) {
        logger.info("北京银行不支持用户名登录方式，taskKey:{}, loginType:{}", context.get(LUA_TASK_KEY),
            context.get(LUA_TASK_LOGIN_TYPE));
        throw new BankException(BALO_99604_25, errorMsgMap.get(BALO_99604_25));
    } else if (equals(LoginType.MOBILE,LoginType.stringToLoginType(context.get(LUA_TASK_LOGIN_TYPE)))) {
        logger.info("北京银行不支持手机号登录方式，taskKey:{}, loginType:{}", context.get(LUA_TASK_KEY),
            context.get(LUA_TASK_LOGIN_TYPE));
        throw new BankException(BALO_99604_10, errorMsgMap.get(BALO_99604_10));
    } else {
        logger.info("北京银行不支持该登录方式，taskKey:{}, loginType:{}", context.get(LUA_TASK_KEY),
            context.get(LUA_TASK_LOGIN_TYPE));
        throw new BankException(BALO_22102_10, errorMsgMap.get(BALO_22102_10));
    }
}


























var luaFuncs = {
    /**
     * 卡号密码
     * @param username
     * @param password
     * @return
     */
    input_account: function (username, password) {
        var map = new HashMap();
        map.put("method", "input_account");
        map.put("username", username);
        map.put("password", password);
        return sendAndReceive(map);
    },
    checkIfInput : function(id,value){
        var map = new LinkedHashMap();
        map.put("method", "checkIfInput");
        map.put("id", id);
        map.put("value", value);
        return Boolean.valueOf(sendAndReceive(map));
    },

    /**
     * 登录按钮
     * @return
     */
    clickLoginBtn: function () {
        var map = new HashMap();
        map.put("method", "clickLoginBtn");
        return sendAndReceive(map);
    },
    /**
     * 刷新验证码的方法
     * @return
     */
    refeshImg: function () {
        var map = new HashMap();
        map.put("method", "refeshImg");
        return sendAndReceive(map);
    },

    /*
     * 帐户信息
     */
    accountInfo: function () {
        var map = new HashMap();
        map.put("method", "accountInfo");
        return sendAndReceive(map);
    },
    /*
     * 帐户信息
     */
    clickSms: function () {
        var map = new HashMap();
        map.put("method", "clickSms");
        return sendAndReceive(map);
    },
    /**
     * 保存图片
     * @return
     */
    store_Img: function () {
        var map = new HashMap();
        map.put("method", "store_Img");
        return sendAndReceive(map);
    },

    recevice: function () {
        var str = lp.Receive();
        if (StringUtils.isBlank(str)) {
            return "";
        }
        return str;
    }
}
